#!/usr/bin/env python3
"""Download Our World in Data COVID dataset and save to data/"""
import os
import requests
import pandas as pd

URLS = [
    "https://covid.ourworldindata.org/data/owid-covid-data.csv",
    # fallback mirror on GitHub raw (mirror of owid covid repo)
    "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv",
]
OUT = "data/owid-covid-data.csv"


def download(urls=URLS, out=OUT):
    os.makedirs(os.path.dirname(out), exist_ok=True)
    last_err = None
    for url in urls:
        print(f"Attempting download {url} -> {out}")
        try:
            resp = requests.get(url, stream=True, timeout=30)
            resp.raise_for_status()
            with open(out, 'wb') as f:
                for chunk in resp.iter_content(1024*1024):
                    if chunk:
                        f.write(chunk)
            print('Download complete')
            return
        except Exception as e:
            print(f"Failed to download from {url}: {e}")
            last_err = e
            # try next URL
    # If we reach here, all urls failed
    raise RuntimeError(f"All download attempts failed. Last error: {last_err}")


def summary(out=OUT):
    df = pd.read_csv(out)
    print('rows,cols =', df.shape)
    print(df.head().to_string())


if __name__ == '__main__':
    download()
    summary()
